﻿using System;
using System.Collections.Generic;
using System.Linq;
using Simple.Data;
using Model.User;

namespace Model.Course
{
    public class SolvedTask
    {
        protected String content;
        protected Int32 id;
        protected Int32 mark;
        protected Int32 taskId;
        protected Int32 studentId;

        protected SolvedTask(Int32 id, String content, Int32 mark, Int32 task, Int32 student)
        {
            this.id = id;
            this.content = content;
            this.mark = mark;
            this.taskId = task;
            this.studentId = student;
        }

        public static SolvedTask create(Student student, Task task, String content)
        {
            var db = Database.Open();
            if (db.SolvedTask.GetCountByTask(task.getId()) > 0)
            {
                db.SolvedTask.DeleteByTask(task.getId());
            }

            var solvedTask = db.SolvedTask.Insert(Content: content, Mark: null, 
                Task: task.getId(), Student: student.getId());

            return new SolvedTask(solvedTask.id, solvedTask.content, 
                                  0, solvedTask.task, solvedTask.student);
        }

        public static SolvedTask get(Student student, Task task)
        {
            var db = Database.Open();

            var st = db.SolvedTask.FindAll(db.SolvedTask.student == student.getId() && db.SolvedTask.task == task.getId()).
                                    FirstOrDefault();

            if (st != null)
                return new SolvedTask(st.id, st.content, (st.mark == null ? 0 : st.mark), st.task, st.student);

            return null;
        }

        public void addAttachment(String fileName, String filePath)
        {
            Attachment a = Attachment.create(fileName, filePath);

            a.setOwnerId(Attachment.OwnerType.SolvedTask, id);
        }

        public String getContent()
        {
            return content;
        }

        public void setContent(String content)
        {
            this.content = content;
            Database.Open().SolvedTask.UpdateById(Id: id, Content: content);
        }

        public Int32 getMark()
        {
            return mark;
        }

        public void setMark(Int32 mark)
        {
            this.mark = mark;
            Database.Open().SolvedTask.UpdateById(Id: id, Mark: mark);
        }

        public int getId()
        {
            return id;
        }

        public int getTaskId()
        {
            return taskId;
        }
    }
}